package com.gitee.cirnochat.common.config;

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.gitee.cirnochat.common.handler.GenericEnumTypeHandler;
import com.gitee.cirnochat.common.model.enums.BaseEnum;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.filter.AssignableTypeFilter;

import java.util.Set;

@Configuration
public class EnumTypeHandlerAutoRegisterConfig {

    private static final String ENUM_PACKAGE = "cirno.chat.model.enums"; // 👈 改成你自己枚举所在的包

    @Bean
    public ConfigurationCustomizer enumHandlerCustomizer() {
        return configuration -> {
            TypeHandlerRegistry registry = configuration.getTypeHandlerRegistry();

            // 创建扫描器
            ClassPathScanningCandidateComponentProvider scanner =
                    new ClassPathScanningCandidateComponentProvider(false);
            scanner.addIncludeFilter(new AssignableTypeFilter(BaseEnum.class));

            // 扫描包下所有实现了 BaseEnum 的类
            Set<BeanDefinition> candidates = scanner.findCandidateComponents(ENUM_PACKAGE);
            for (BeanDefinition bd : candidates) {
                try {
                    Class<?> clazz = Class.forName(bd.getBeanClassName());
                    if (clazz.isEnum()) {
                        registry.register(clazz, GenericEnumTypeHandler.class);
                        System.out.printf("✅ 注册枚举 %s 类型处理器%n",clazz.getSimpleName());
                    }
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException("无法加载枚举类: " + bd.getBeanClassName(), e);
                }
            }
        };
    }
}
